package com.cloud.core.exception;


import cn.hutool.core.util.ObjectUtil;
import com.cloud.core.constant.ErrorCodeConstant;
import com.cloud.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author dhaigang
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(RuntimeException.class)
	public R<Void> handleRuntimeException(RuntimeException e){
		log.error("发生未知异常:{}",e.getMessage(),e);
		if (e.getCause()instanceof MyException){
			return R.failed(((MyException) e.getCause()).getCode() != null ? ((MyException) e.getCause()).getCode() : ErrorCodeConstant.FAIL ,e.getCause().getMessage());
		}
		return R.failed(ErrorCodeConstant.FAIL,"业务异常");
	}

	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(MyException.class)
	public R<Void>  handleException(MyException e){
		log.error("发生系统异常:{}",e.getMessage(),e);
		return R.failed(ObjectUtil.isNotNull(e.getCode())?e.getCode():ErrorCodeConstant.FAIL,e.getMessage());
	}


	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	@ExceptionHandler(BindException.class)
	public R<Void>handleBindException(BindException e){
		log.error(e.getMessage(),e);
		String message=e.getAllErrors().get(0).getDefaultMessage();
		return R.failed(message);
	}

	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ResponseEntity<R>   handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
		log.error(e.getMessage(),e);
		String message=e.getBindingResult().getFieldError().getDefaultMessage();
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(R.failed(ErrorCodeConstant.FORMAT_ERROR,message));
	}

	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = HttpMessageNotReadableException.class)
	public R<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
		log.error("JSON格式校验失败'{}'", e.getMessage());
		return R.failed(ErrorCodeConstant.FORMAT_ERROR, "格式错误，请检查数据");
	}



}